package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexPatterns;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        // TODO 1.校验手机号是否合法
        if(RegexUtils.isPhoneInvalid(phone)) return Result.fail("手机号格式错误!");
        // TODO 2.发送验证码
        String code = RandomUtil.randomNumbers(6);
        // TODO 3.保存验证码到session
        session.setAttribute("code", code);
        // TODO 4.发送验证码
        log.debug("发送验证码成功，验证码：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        // TODO 1.校验手机号是否合法
        if(RegexUtils.isPhoneInvalid(loginForm.getPhone())) return Result.fail("手机号格式错误!");
        // TODO 2.校验验证码是否合法
        if(RegexUtils.isCodeInvalid(loginForm.getCode())) return Result.fail("验证码格式错误!");
        // TODO 3.校验验证码是否一致
        String cacheCode = (String) session.getAttribute("code");
        if(cacheCode == null || !cacheCode.equals(loginForm.getCode())) return Result.fail("验证码错误!");
        // TODO 4.查询用户是否已经存在
        User user = query().eq("phone", phone).one();
        if(user != null) return Result.fail("该手机号已经注册！");
        // TODO 5.保存新用户信息
        user = new User();
        user.setPhone(phone);
        user.setNickName("用户" + RandomUtil.randomNumbers(6));
        save(user);
        return null;
    }
}
